﻿using iOSForLife.Data;
using iOSForLife.Data.Models;
using iOSForLife.WebAPI.IdentityModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace iOSForLife.WebAPI.Controllers;

[ApiController]
[Route("[controller]")]
public class TodoController(
    IDbContextFactory<LifeContext> dbContextFactory,
    IHttpContextAccessor httpContextAccessor) : ControllerBase
{
    [TokenActionFilter]
    [Authorize]
    [HttpPost]
    public async Task<IActionResult> AddOrUpdate([FromBody] TodoModel model)
    {
        var member = httpContextAccessor.HttpContext?.User.GetUser();
        if (member == null) return NotFound("用户未登录或验证已超时");

        await using var context = await dbContextFactory.CreateDbContextAsync();
        member =
            await context.Users.FirstOrDefaultAsync(x => x.UserId == member.UserId);
        if (member == null) return NotFound("找不到用户");

        if (string.IsNullOrEmpty(model.StartTime))
        {
            model.StartTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        if (string.IsNullOrEmpty(model.EndTime))
        {
            model.EndTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }

        if (string.IsNullOrEmpty(model.Id))
        {
            model.Id = model.ToHash();
            member.Todos.Add(model);
        }
        else
        {
            var todo = await context.Todos.FirstOrDefaultAsync(x => x.Id == model.Id);
            if (todo == null) return NotFound("找不到待办事项");
            todo.Update(model);
        }

        await context.SaveChangesAsync();
        return Ok();
    }

    [TokenActionFilter]
    [Authorize]
    [HttpGet]
    public async Task<IActionResult> Delete(string id)
    {
        var member = httpContextAccessor.HttpContext?.User.GetUser();
        if (member == null) return NotFound("用户未登录或验证已超时");

        await using var context = await dbContextFactory.CreateDbContextAsync();
        var model = await context.Todos.FirstOrDefaultAsync(x => x.Id == id && x.UserId == member.UserId);

        if (model == null)
        {
            return NotFound("找不到待办事项");
        }

        context.Todos.Remove(model);
        await context.SaveChangesAsync();

        return Ok();
    }
}